/**
 * @see https://umijs.org/docs/max/access#access
 * */
export default function access(
  initialState: { currentUser?: API.UserWithRoles } | undefined,
) {
  const { currentUser } = initialState ?? {};

  // 获取用户的所有权限编码
  const userPermissions =
    currentUser?.permissions?.map((p) => p.code || '') || [];
  const userRoles = currentUser?.roles?.map((r) => r.code || '') || [];

  return {
    // 基础权限检查
    canAdmin: currentUser && currentUser.access === 'admin',
    canUser: !!currentUser?.userid,

    // 基于角色的权限检查
    isAdmin: userRoles.includes('admin'),
    isEditor: userRoles.includes('editor'),
    isViewer: userRoles.includes('viewer'),

    // 基于权限编码的检查
    hasPermission: (permission: string) => userPermissions.includes(permission),

    // 菜单权限检查
    canViewDashboard: userPermissions.includes('dashboard:view'),
    canViewUsers: userPermissions.includes('user:view'),
    canCreateUser: userPermissions.includes('user:create'),
    canEditUser: userPermissions.includes('user:edit'),
    canDeleteUser: userPermissions.includes('user:delete'),
    canAssignUserRole: userPermissions.includes('user:assign_role'),

    canViewRoles: userPermissions.includes('role:view'),
    canCreateRole: userPermissions.includes('role:create'),
    canEditRole: userPermissions.includes('role:edit'),
    canDeleteRole: userPermissions.includes('role:delete'),
    canConfigureRolePermission: userPermissions.includes(
      'role:configure_permission',
    ),

    canViewPermissions: userPermissions.includes('permission:view'),
    canCreatePermission: userPermissions.includes('permission:create'),
    canEditPermission: userPermissions.includes('permission:edit'),
    canDeletePermission: userPermissions.includes('permission:delete'),

    canViewSettings: userPermissions.includes('setting:view'),
    canEditSettings: userPermissions.includes('setting:edit'),

    // 功能权限检查
    canManageSystem:
      userPermissions.includes('system:manage') || userRoles.includes('admin'),
    canExportData: userPermissions.includes('data:export'),
    canImportData: userPermissions.includes('data:import'),

    // 通用权限检查方法
    hasAnyPermission: (permissions: string[]) =>
      permissions.some((p) => userPermissions.includes(p)),

    hasAllPermissions: (permissions: string[]) =>
      permissions.every((p) => userPermissions.includes(p)),

    hasAnyRole: (roles: string[]) => roles.some((r) => userRoles.includes(r)),

    hasAllRoles: (roles: string[]) => roles.every((r) => userRoles.includes(r)),
  };
}
